//网络请求封装
import 'package:dio/dio.dart';
import 'package:shenling_project/utils/eventBus.dart';

import 'tokenManager.dart';
// import 'package:enjoy_plus_hm/utils/eventBus.dart';
// import 'package:enjoy_plus_hm/utils/token.dart';

class NetworkService {
  final _dio = Dio();

  //构造函数
  NetworkService() {
    //设置基地址
    _dio.options.baseUrl = 'https://slwl-api.itheima.net';
    //设置连接超时时间
    _dio.options.connectTimeout = const Duration(seconds: 5);
    //设置接收超时时间
    _dio.options.receiveTimeout = const Duration(seconds: 5);
    //设置请求头
    _dio.options.headers = {'Content-Type': 'application/json'};
    //添加拦截器
    _addInterceptors();
  }

  //添加拦截器
  void _addInterceptors() {
    _dio.interceptors.add(
      InterceptorsWrapper(
        onRequest: (options, handler) async {
          // 请求拦截器：添加公共请求参数、token 等
          //先获取token
          final token = TokenManager().getToken() ?? '';
          // //判断token 是否为空
          if (token.isNotEmpty) {
            //添加token到请求头中
            options.headers['Authorization'] = token;
          }
          return handler.next(options);
        },
        onResponse: (response, handler) {
          // 响应拦截器：统一处理成功响应
          return handler.next(response);
        },
        onError: (DioException error, handler) {
          // 响应拦截器：统一处理错误响应
          return handler.next(error);
        },
      ),
    );
  }

  //封装请求request方法
  Future<dynamic> request(
    String method,
    String path,
    dynamic data,
    Map<String, dynamic>? queryParameters,
  ) async {
    try {
      Response response = await _dio.request(
        path,
        data: data,
        queryParameters: queryParameters,
        options: Options(method: method),
      );
      return handleResponse(response);
    } on DioException catch (e) {
      return handleError(e);
    }
  }

  ///  get  post  put  delete
  /// get请求
  Future<dynamic> get(String url, {Map<String, dynamic>? params}) async {
    try {
      final res = await _dio.get(url, queryParameters: params);
      return handleResponse(res);
    } catch (e) {
      handleError(e);
    }
  }

  //post
  //post请求
  Future<dynamic> post(String url, {dynamic data}) async {
    try {
      final res = await _dio.post(url, data: data);
      return handleResponse(res);
    } catch (e) {
      handleError(e);
    }
  }

  // put请求
  Future<dynamic> put(String url, {Map<String, dynamic>? data}) async {
    try {
      final res = await _dio.put(url, data: data);
      return handleResponse(res);
    } catch (e) {
      handleError(e);
    }
  }

  // delete请求
  Future<dynamic> delete(String url, {Map<String, dynamic>? data}) async {
    try {
      final res = await _dio.delete(url, data: data);
      return handleResponse(res);
    } catch (e) {
      handleError(e);
    }
  }

  //成功的结果
  dynamic handleResponse(Response response) {
    if (response.statusCode! >= 200 && response.statusCode! < 300) {
      return response.data;
    } else {
      throw Exception('请求失败，状态码：${response.statusCode}');
    }
  }

  //失败的结果
  dynamic handleError(error) async {
    if (error is DioException) {
      if (error.type == DioExceptionType.connectionTimeout ||
          error.type == DioExceptionType.receiveTimeout) {
        throw Exception('网络连接超时');
      } else if (error.type == DioExceptionType.badResponse) {
        //处理token401的请求
        if (error.response?.statusCode == 401) {
          //清除token
          await TokenManager().removeToken();
          //跳转登录页
          event.fire(LogoutGetData());
        } else {
          throw Exception('响应错误，状态码：${error.response?.statusCode}');
        }
      } else {
        throw Exception('网络请求错误：$error');
      }
    } else {
      throw Exception('未知错误：$error');
    }
  }
}

//导出
final http = NetworkService();
